package com.netty.client;

import com.netty.client.handler.MessageClientHandler;
import com.netty.client.handler.PersonClientHandler;
import com.netty.entity.Message;
import com.netty.entity.Person;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.util.ReferenceCountUtil;

import java.io.BufferedReader;
import java.io.InputStreamReader;

/**
 * @author xurongbei
 */
public class NettyClient {

    private EventLoopGroup group = null;

    private Bootstrap bootstrap = null;

    public NettyClient() {
        init();
    }

    private void init(){
        group=new NioEventLoopGroup();
        bootstrap=new Bootstrap();
        bootstrap.group(group);
        bootstrap.channel(NioSocketChannel.class);
    }

    public ChannelFuture doRequest(String host, int port, final ChannelHandler... handlers) throws InterruptedException
    {
        this.bootstrap.handler(new ChannelInitializer<SocketChannel>() {

            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                ch.pipeline().addLast(handlers);

            }
        });
        ChannelFuture future=this.bootstrap.connect(host,port).sync();
        return future;
    }
    public void release(){
        this.group.shutdownGracefully();
    }

    public static void main(String[] args) {
        NettyClient client=null;
        ChannelFuture future=null;
        try{
            client=new NettyClient();
            future=client.doRequest("localhost", 9999, new MessageClientHandler(),new PersonClientHandler());
            //Scanner s=null;
            System.out.println("11111111");
            Person person = new Person();
            person.setName("许荣北");
            person.setAge(12);
            Message message = new Message();
            message.setContent("我说许荣北");
            message.setTitle("您好");
            future.channel().writeAndFlush(message);
            //future.channel().writeAndFlush(Unpooled.copiedBuffer("连接成功".getBytes("UTF-8")));
            //future.channel().writeAndFlush(Unpooled.copiedBuffer(line.getBytes("UTF-8")));
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            if(null!=future)
            {
                try{
                    future.channel().closeFuture().sync();
                }catch(InterruptedException e){
                    e.printStackTrace();
                }
            }
            if(null != client)
            {
                client.release();
            }
        }
    }

}
